package com.yc.vcode.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.vcode.bean.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//拦截器
public class VcodeInterceptor implements HandlerInterceptor {

    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object vcode = session.getAttribute("vcode");
        if(vcode == null){
            sendResult(response, new Result(0, "验证码失效，请重新获取验证码", null));
            return false;
        }
        String vcode1 = request.getParameter("vcode");
        if(vcode1 == null){
            sendResult(response, new Result(0, "请先输入验证码!", null));
            return false;
        }
        if(vcode.equals(vcode1) == false){
            sendResult(response, new Result(0, "验证码输入错误!", null));
            return false;
        }
        return true;
    }


    private void sendResult(HttpServletResponse response, Result result){
        response.setContentType("application/json;charset=utf-8");
        //json工具
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().println(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
